<style>
    #dm_tool:hover{
        color: red;
    }
    #dm_login:hover{
        background: #00CE6F !important;
    }
    input,select{
        color: red;
    }
</style>
<div id="dm_tool" style="height: 80px;width: 80px;border-radius: 80px;line-height: 80px;text-align:center;background: rgba(0,0,0,0.5);position: fixed;top:20px;;right: 20px;cursor: pointer;z-index: 99999;color: #00CE6F;display: none1">
    打开
</div>
<div id="dm_main" style="min-height: 200px;width: 220px;border-radius: 5px;background: rgba(0,0,0,0.5);position: fixed;top:120px;right: 20px;display: none;z-index: 10000;color: red;display: none">
    <div style="height: 20px;line-height: 20px;background: #1cee9d;border-top-right-radius: 5px;border-top-left-radius: 5px;text-align: center;color: #000;">
        又见平遥辅助v2.1
    </div>
    <div id="dm_login_box" style="padding: 10px;display: none">
        <div style="margin: 5px 0">
            账号:<input id="dm_user" value="" style="color: red">
        </div>
        <div style="margin: 5px 0">
            密码:<input id="dm_pass" value="" type="password" style="color: red">
        </div>
        <div style="margin: 5px 0;text-align: center">
            <img id="dm_login_code" src="" alt="请稍后,或点击刷新">
        </div>
        <div style="margin: 5px 0">
            验证码:<input id="dm_code" style="" style="color: red;">
        </div>
        <div style="margin: 5px 0">
            手输码:<input id="dm_code_hand" style="" style="color: red;">
        </div>
        <div id="dm_login_error" style="line-height: 20px;text-align: center;color: red">

        </div>
        <div style="margin: 5px">
            <div id="dm_login" style="height: 30px;line-height: 30px;text-align: center;background: #00b7ee;color: #fff;cursor: pointer">登录</div>
        </div>
        <div id="dm_login_tips" style="text-align: center;color: red;font-size: 12px;background: #3b3b3b">

        </div>
    </div>

    <div id="dm_tool_main" style="padding: 10px;color: #fff;display: none1">
        <div style="text-align: right;margin-bottom: 10px;">
            <span id="dm_logout"  style="background: #ce1823;color: #fff;padding: 3px 5px;cursor: pointer">退出系统</span>
            <span id="dm_reload"  style="background: #00CE6F;color: #fff;padding: 3px 5px;cursor: pointer">刷新页面</span>
            <span id="dm_rebook"  style="background: #2487ce;color: #fff;padding: 3px 5px;cursor: pointer">重构交易</span>
        </div>
        <div style="text-align: left;margin-bottom: 10px;">
            <span id="dm_save_config"  style="background: #ce9224;color: #fff;padding: 3px 5px;cursor: pointer;margin-top: 5px;width: 100%">保存配置</span>
        </div>

        <div style="margin: 5px 0">
            自动:
            <select id="dm_auto_start" style="color: red">
                <option value="0">手动开始</option>
                <option value="1">自动开始</option>
            </select>
        </div>

        <div style="margin: 5px 0">
            交易号:<input id="dm_transNo" placeholder="勿填,自动读取" readonly style="color: red">
        </div>


        <div style="margin: 5px 0">
            日期:<input id="dm_date" type="date" style="color: red">
        </div>
        <div style="margin: 5px 0">
            场次:
            <select id="dm_screenNo" style="color: red">
                <option value="1">第1场</option>
                <option value="2">第2场</option>
                <option value="3">第3场</option>
                <option value="4">第4场</option>
                <option value="5">第5场</option>
                <option value="6">第6场</option>
                <option value="7">第7场</option>
                <option value="8">第8场</option>
                <option value="9">第9场</option>
                <option value="10">第10场</option>
            </select>
        </div>
        <div style="margin: 5px 0">
            张数:<input id="dm_ticket_num" value="1" style="color: red">
        </div>

        <div style="margin: 5px 0">
            间隔:
            <select id="dm_timer" style="color: red">
                <option value="2">1秒</option>
                <option value="2">2秒</option>
                <option value="3">3秒</option>
                <option value="4">4秒</option>
                <option value="5">5秒</option>
                <option value="6">6秒</option>
                <option value="7">7秒</option>
                <option value="8">8秒</option>
                <option value="9">9秒</option>
                <option value="10">10秒</option>
                <option value="15">15秒</option>
                <option value="20">20秒</option>
                <option value="30">30秒</option>
                <option value="40">40秒</option>
                <option value="50">50秒</option>
                <option value="60">60秒</option>
            </select>
        </div>



        <div style="margin: 5px 0">
            身份证:<input id="dm_sfz_id" value="" style="color: red;font-size: 10px">
        </div>

        <div style="margin: 5px 0">
            下单冻结:
            <select id="dm_timer_order" style="color: red">
                <option value="999999">不自动付款</option>
                <option value="0.01">0秒</option>
                <option value="1">1秒</option>
                <option value="2">2秒</option>
                <option value="3">3秒</option>
                <option value="4">4秒</option>
                <option value="5">5秒</option>
                <option value="6">6秒</option>
                <option value="7">7秒</option>
                <option value="8">8秒</option>
                <option value="9">9秒</option>
                <option value="10">10秒</option>
                <option value="11">11秒</option>
                <option value="12">12秒</option>
                <option value="13">13秒</option>
                <option value="14">14秒</option>
                <option value="15">15秒</option>
            </select>
        </div>

        <div style="margin: 5px">
            <div id="dm_test" style="height: 30px;line-height: 30px;text-align: center;background: #00b7ee;color: #fff;cursor: pointer">开始抢票</div>
        </div>
        <div style="margin: 5px 0">
            循环:<input id="dm_loop_num" value="暂无" readonly style="color: red">次
        </div>
        <div style="margin: 5px 0">
            余票:<input id="dm_screen_remainNum" value="暂无" style="color: red">张
        </div>

        <div style="margin: 5px 0">
            抢票:<input id="dm_book_num" value="暂无" style="color: red">张
        </div>

        <div id="book_box" style="display: none">

            <!--<div style="margin: 5px">-->
            <!--<div id="dm_book" style="height: 30px;line-height: 30px;text-align: center;background: #00b7ee;color: #fff;cursor: pointer">立即订票</div>-->
            <!--</div>-->

            <div style="margin: 5px 0">
                预订单号:<input id="dm_book_order_id" style="width: 100px;color: red" >
            </div>

            <div style="margin: 5px 0;text-align: center">
                <img id="dm_book_code_img" src="" alt="请稍后,或点击刷新">
            </div>
            <div style="margin: 5px 0">
                验证码:<input id="dm_book_code" style="color: red">
            </div>

            <div style="margin: 5px">
                <div id="dm_book_pay" style="height: 30px;line-height: 30px;text-align: center;background: #31b24f;color: #fff;cursor: pointer">自动打码支付</div>
            </div>


            <div style="margin: 5px 0">
                验证码:<input id="dm_book_code_hand" style="color: red">
            </div>
            <div style="margin: 5px">
                <div id="dm_book_pay_hand" style="height: 30px;line-height: 30px;text-align: center;background: #b2314b;color: #fff;cursor: pointer">手动填码支付</div>
            </div>
        </div>
        <div id="dm_booking" style="text-align: center;color: red;font-size: 12px;background: #3b3b3b">

        </div>
    </div>

</div>

<div id="dm_can_book1" class="dm_tips" style="height: 300px;width: 300px;border-radius: 300px;line-height: 300px;text-align:center;position: fixed;top:50%;left: 50%;margin-top:-150px;margin-left:-150px;background: rgb(22,190,124);font-size:25px;color:#fff;display: none;z-index: 99999">
    有足够票！快下单！
    <audio controls id="MyAudio1" hidden>
        <source src="http://video_api.dmgc.us/youjian/2.wav" type="audio/mpeg">
        您的浏览器不支持该音频格式。
    </audio>
    <audio controls id="MyAudio2" hidden>
        <source src="http://video_api.dmgc.us/youjian/msg.mp3" type="audio/mpeg">
        您的浏览器不支持该音频格式。
    </audio>
</div>

<div id="dm_can_book2" class="dm_tips"  style="height: 300px;width: 300px;border-radius: 300px;line-height: 300px;text-align:center;position: fixed;top:50%;left: 50%;margin-top:-150px;margin-left:-150px;background: rgb(255,8,28);font-size:25px;color:#fff;display: none;z-index: 99999">
    有票！数量不够！
</div>

<script>

    $('#dm_user').val(localStorage.getItem("dm_user"));
    $('#dm_pass').val(localStorage.getItem("dm_pass"));
    $('#dm_sfz_id').val(localStorage.getItem("dm_sfz_id"));
    $('#dm_date').val(localStorage.getItem("dm_date"));
    $('#dm_ticket_num').val(localStorage.getItem("dm_ticket_num"));
    $('#dm_screenNo').val(localStorage.getItem("dm_target_screenNo"));
    $('#dm_auto_start').val(localStorage.getItem("dm_auto_start"));
    $('#dm_timer_order').val(localStorage.getItem("dm_timer_order"));

</script>

<script>
    function Predict(img_data, img_enc, app_id, app_key, usr_id, usr_key, predict_type, pred_cb){
        var curDate = new Date();
        timestamp	= parseInt(curDate.getTime() / 1000).toString();
        sign 		= CalcSign( usr_id, usr_key, timestamp);
        //console.log("识别请求，当前时间戳为：" + timestamp + " usr_id: " + usr_id + " usr_key: " + usr_key + " checksum: " + sign);
        //encode_img	= EncodeImgData( img_data, img_enc);
        encode_img = img_data;
        console.log("img_data: " + encode_img);
        params 		= {
            'user_id':usr_id,
            'timestamp':timestamp,
            'sign': sign,
            'predict_type': predict_type,
            'img_data': encode_img
        }
        if( app_id !== null || app_id !== undefined || app_id !== ''){
            asign 	= CalcSign( app_id, app_key, timestamp);
            params['appid'] = app_id;
            params['asign'] = asign;
        }
        url 		= "http://pred.fateadm.com/api/capreg"
        ajaxPost(url, params, function(ret_code, rsp_str){
            if( ret_code == 0){
                rsp_data			= eval('('+rsp_str + ')');
                var pred_data		= {};
                if( rsp_data.RetCode == 0){
                    pred_data 		= eval('(' + rsp_data.RspData + ')');
                }
                pred_cb( rsp_data.RetCode, rsp_data, pred_data);
            }else{
                rsp_data 		= {};
                rsp_data.ErrMsg = rsp_str;
                rsp_data.RetCode = ret_code;
                pred_cb( ret_code, rsp_data, {});
            }
        })
    }

    /*
    *	Justice     	退款请求
    *		user_id 		用户id
    *		usr_key			访问秘钥
    *		request_id 		退款序号
    *		pred_cb			结果数据回调
                    pred_cb( ret_code, rsp_data)
                        ret_code: 		0 成功
                                        -1 访问失败,http 访问失败
                                        -2 超时
                                        其他 详见错误页http://docs.fateadm.com/index.php?s=/1&page_id=5
                        rsp_data		访问返回结果
                                        RetCode    与参数1的ret_code意思一致
                                        ErrMsg 		当ret_code非0时，保存错误信息

    */
    function Justice( usr_id, usr_key, request_id, res_cb){
        var curDate = new Date();
        timestamp	= parseInt(curDate.getTime() / 1000).toString();
        sign 		= CalcSign( usr_id, usr_key, timestamp);
        //console.log("退款请求，当前时间戳为：" + timestamp + " usr_id: " + usr_id + " usr_key: " + usr_key + " checksum: " + sign);
        params 		= {
            'user_id':usr_id,
            'timestamp':timestamp,
            'sign': sign,
            'request_id': request_id
        };
        url 		= "http://pred.fateadm.com/api/capjust";
        ajaxPost(url, params, function(ret_code, rsp_str){
            if( ret_code == 0){
                rsp_data			= eval('('+rsp_str + ')');
                res_cb( rsp_data.RetCode, rsp_data);
            }else{
                rsp_data 		= {};
                rsp_data.ErrMsg = rsp_str;
                rsp_data.RetCode = ret_code;
                res_cb( ret_code, rsp_data);
            }
        })
    }

    /*
    *	Predict     	查询余额请求
    *		user_id 		用户id
    *		usr_key			访问秘钥
    *		pred_cb			结果数据回调
                    pred_cb( ret_code, rsp_data)
                        ret_code: 		0 成功
                                        -1 访问失败,http 访问失败
                                        -2 超时
                                        其他 详见错误页http://docs.fateadm.com/index.php?s=/1&page_id=5
                        rsp_data		访问返回结果
                                        RetCode    与参数1的ret_code意思一致
                                        ErrMsg 		当ret_code非0时，保存错误信息
                                        cust_val   账上余额

    */
    function QueryBalance(usr_id, usr_key, res_cb){
        var curDate = new Date();
        timestamp	= parseInt(curDate.getTime() / 1000).toString();
        sign 		= CalcSign( usr_id, usr_key, timestamp);
        //console.log("查询余额请求，当前时间戳为：" + timestamp + " usr_id: " + usr_id + " usr_key: " + usr_key + " checksum: " + sign);
        params 		= {
            'user_id':usr_id,
            'timestamp':timestamp,
            'sign': sign
        };
        url 		= "http://pred.fateadm.com/api/custval";
        ajaxPost(url, params, function(ret_code, rsp_str){
            if( ret_code == 0){
                rsp_data			= eval('('+rsp_str + ')');
                if( rsp_data.RetCode == 0){
                    var bal_res 	= eval('(' + rsp_data.RspData + ')');
                    rsp_data.cust_val = bal_res.cust_val;
                }
                res_cb( rsp_data.RetCode, rsp_data);
            }else{
                rsp_data 		= {};
                rsp_data.ErrMsg = rsp_str;
                rsp_data.RetCode = ret_code;
                res_cb( ret_code, rsp_data);
            }
        })
    }

    /*
    *	Charge     	充值余额请求
    *		user_id 		用户id
    *		usr_key			访问秘钥
    *		cardid			充值卡id
    *		cardkey			充值卡密
    *		pred_cb			结果数据回调
                    pred_cb( ret_code, rsp_data)
                        ret_code: 		0 成功
                                        -1 访问失败,http 访问失败
                                        -2 超时
                                        3023 充值卡已使用
                                        其他 详见错误页http://docs.fateadm.com/index.php?s=/1&page_id=5
                        rsp_data		访问返回结果
                                        RetCode    与参数1的ret_code意思一致
                                        ErrMsg 		当ret_code非0时，保存错误信息

    */
    function Charge(usr_id, usr_key, cardid, cardkey, res_cb){
        var curDate = new Date();
        timestamp	= parseInt(curDate.getTime() / 1000).toString();
        sign 		= CalcSign( usr_id, usr_key, timestamp);
        csign       = hex_md5( usr_key + timestamp + cardid + cardkey);
        console.log("充值");
        params      = {
            'user_id':usr_id,
            'timestamp':timestamp,
            'sign':sign,
            'cardid':cardid,
            'csign':csign
        };
        url         = "http://pred.fateadm.com/api/charge";
        ajaxPost(url, params, function(ret_code, rsp_str){
            if( ret_code == 0){
                rsp_data			= eval('('+rsp_str + ')');
                res_cb( rsp_data.RetCode, rsp_data);
            }else{
                rsp_data 		= {};
                rsp_data.ErrMsg = rsp_str;
                rsp_data.RetCode = ret_code;
                res_cb( ret_code, rsp_data);
            }
        })
    }

    /*
    *	QueryRTT     	查询网络延迟
    *			客户端计算从调用开始到结束返回的时候的时间消耗，获得网络交互的总时间
    *		app_id 			app id
    *		app_key 		app秘钥
    *		user_id 		用户id
    *		usr_key			访问秘钥
    *		predict_type 	验证码类型
    *		pred_cb			结果数据回调
                    pred_cb( ret_code, rsp_data)
                        ret_code: 		0 成功
                                        -1 访问失败,http 访问失败
                                        -2 超时
                                        其他 详见错误页http://docs.fateadm.com/index.php?s=/1&page_id=5
                        rsp_data		访问返回结果
                                        RetCode    与参数1的ret_code意思一致
                                        ErrMsg 		当ret_code非0时，保存错误信息

    */
    function QueryRTT(app_id, app_key, usr_id, usr_key, predict_type, pred_cb){
        var curDate = new Date();
        timestamp	= parseInt(curDate.getTime() / 1000).toString();
        sign 		= CalcSign( usr_id, usr_key, timestamp);
        params 		= {
            'user_id':usr_id,
            'timestamp':timestamp,
            'sign': sign,
            'predict_type': predict_type
        }
        if( app_id !== null || app_id !== undefined || app_id !== ''){
            asign 	= CalcSign( app_id, app_key, timestamp);
            params['appid'] = app_id;
            params['asign'] = asign;
        }
        url 		= "http://pred.fateadm.com/api/qcrtt"
        ajaxPost(url, params, function(ret_code, rsp_str){
            if( ret_code == 0){
                rsp_data			= eval('('+rsp_str + ')');
                pred_cb( rsp_data.RetCode, rsp_data);
            }else{
                rsp_data 		= {};
                rsp_data.ErrMsg = rsp_str;
                rsp_data.RetCode = ret_code;
                pred_cb( ret_code, rsp_data);
            }
        })
    }

    function CalcSign(usr_id, usr_key, timestamp){
        md5_chk		= hex_md5(timestamp + usr_key);
        sign_chk	= hex_md5( usr_id + timestamp + md5_chk);
        return sign_chk;
    }

    function EncodeImgData( img_data, enc_flag){
        var str 	= img_data;
        if( enc_flag != true){
            var b 		= new Base64();
            str 		= b.encode(img_data);
        }
        var data 	= encodeURIComponent(str);
        return data;
    }


    // ajax 对象
    function ajaxObject() {
        var xmlHttp;
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            // Internet Explorer
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    //alert("您的浏览器不支持AJAX！");
                    return false;
                }
            }
        }
        return xmlHttp;
    }

    // ajax post请求：
    function ajaxPost ( url , data , fncallback ) {
        var ajax = ajaxObject();
        var timeout = false;
        var timer = setTimeout( function(){
            timeout = true;
            ajax.abort();
        }, 60000 );
        ajax.open( "post" , url , true );
        ajax.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded");
        ajax.onreadystatechange = function () {
            if( ajax.readyState == 4 ) {
                if( timeout ) {
                    // already timeout happened
                    fncallback(-2, "http timeout failed!");
                    return;
                }
                clearTimeout( timer );
                if( ajax.status == 200 ) {
                    fncallback(0, ajax.responseText);
                }
                else {
                    fncallback(-1, "http request failed! http error code: " + ajax.status);
                }
            }
        }
        function DictToSendStr( params){
            var str 	= "";
            var first 	= true;
            for( var i in params){
                if( first){
                    first 	= false;
                }else{
                    str += "&";
                }
                str += i + "=" + params[i];
            }
            return str;
        }
        str_data 		= DictToSendStr( data);
        ajax.send(str_data);
    }

    function ReadFile(file, load_cb) {
        //console.log("read file: " + file);
        var reader = new FileReader();//new一个FileReader实例
        reader.onload = function() {
            // 没做异常判断
            file_data		= this.result;
            file_data		= file_data.split(",");
            file_data		= file_data.pop();
            load_cb( file_data);
        }
        reader.readAsDataURL(file);
    }

</script>

<script>
    /**
     *
     * Base64  encode / decode
     * Md5     hex_md5
     * SHA     hex_sha1
     *
     * @author Fatea
     *
     */
    function Base64() {
        // private property
        _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        // public method for encoding
        this.encode = function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        }
        // public method for decoding
        this.decode = function (input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        }
        // private method for UTF-8 encoding
        _utf8_encode = function (string) {
            string = string.replace(/\r\n/g,"\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
            }
            return utftext;
        }
        // private method for UTF-8 decoding
        _utf8_decode = function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;
            while ( i < utftext.length ) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i+1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i+1);
                    c3 = utftext.charCodeAt(i+2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    }

    /*
     * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
     * Digest Algorithm, as defined in RFC 1321.
     * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
     * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
     * Distributed under the BSD License
     * See http://pajhome.org.uk/crypt/md5 for more info.
     */
    /*
     * Configurable variables. You may need to tweak these to be compatible with
     * the server-side, but the defaults work in most cases.
     */
    var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase  */
    var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
    var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode  */
    /*
     * These are the functions you'll usually want to call
     * They take string arguments and return either hex or base-64 encoded strings
     */
    function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
    function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
    function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
    function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
    function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
    function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
    /*
     * Perform a simple self-test to see if the VM is working
     */
    function md5_vm_test()
    {
        return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
    }
    /*
     * Calculate the MD5 of an array of little-endian words, and a bit length
     */
    function core_md5(x, len)
    {
        /* append padding */
        x[len >> 5] |= 0x80 << ((len) % 32);
        x[(((len + 64) >>> 9) << 4) + 14] = len;
        var a = 1732584193;
        var b = -271733879;
        var c = -1732584194;
        var d = 271733878;
        for(var i = 0; i < x.length; i += 16)
        {
            var olda = a;
            var oldb = b;
            var oldc = c;
            var oldd = d;
            a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
            d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
            c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
            b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
            a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
            d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
            c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
            b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
            a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
            d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
            c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
            b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
            a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
            d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
            c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
            b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
            a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
            d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
            c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
            b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
            a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
            d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
            c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
            b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
            a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
            d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
            c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
            b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
            a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
            d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
            c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
            b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
            a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
            d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
            c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
            b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
            a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
            d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
            c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
            b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
            a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
            d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
            c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
            b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
            a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
            d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
            c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
            b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
            a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
            d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
            c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
            b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
            a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
            d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
            c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
            b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
            a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
            d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
            c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
            b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
            a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
            d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
            c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
            b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
            a = safe_add(a, olda);
            b = safe_add(b, oldb);
            c = safe_add(c, oldc);
            d = safe_add(d, oldd);
        }
        return Array(a, b, c, d);
    }
    /*
     * These functions implement the four basic operations the algorithm uses.
     */
    function md5_cmn(q, a, b, x, s, t)
    {
        return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
    }
    function md5_ff(a, b, c, d, x, s, t)
    {
        return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
    }
    function md5_gg(a, b, c, d, x, s, t)
    {
        return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
    }
    function md5_hh(a, b, c, d, x, s, t)
    {
        return md5_cmn(b ^ c ^ d, a, b, x, s, t);
    }
    function md5_ii(a, b, c, d, x, s, t)
    {
        return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
    }
    /*
     * Calculate the HMAC-MD5, of a key and some data
     */
    function core_hmac_md5(key, data)
    {
        var bkey = str2binl(key);
        if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
        var ipad = Array(16), opad = Array(16);
        for(var i = 0; i < 16; i++)
        {
            ipad[i] = bkey[i] ^ 0x36363636;
            opad[i] = bkey[i] ^ 0x5C5C5C5C;
        }
        var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
        return core_md5(opad.concat(hash), 512 + 128);
    }
    /*
     * Add integers, wrapping at 2^32. This uses 16-bit operations internally
     * to work around bugs in some JS interpreters.
     */
    function safe_add(x, y)
    {
        var lsw = (x & 0xFFFF) + (y & 0xFFFF);
        var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
        return (msw << 16) | (lsw & 0xFFFF);
    }
    /*
     * Bitwise rotate a 32-bit number to the left.
     */
    function bit_rol(num, cnt)
    {
        return (num << cnt) | (num >>> (32 - cnt));
    }
    /*
     * Convert a string to an array of little-endian words
     * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
     */
    function str2binl(str)
    {
        var bin = Array();
        var mask = (1 << chrsz) - 1;
        for(var i = 0; i < str.length * chrsz; i += chrsz)
            bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
        return bin;
    }
    /*
     * Convert an array of little-endian words to a string
     */
    function binl2str(bin)
    {
        var str = "";
        var mask = (1 << chrsz) - 1;
        for(var i = 0; i < bin.length * 32; i += chrsz)
            str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
        return str;
    }
    /*
     * Convert an array of little-endian words to a hex string.
     */
    function binl2hex(binarray)
    {
        var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
        var str = "";
        for(var i = 0; i < binarray.length * 4; i++)
        {
            str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
                hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
        }
        return str;
    }
    /*
     * Convert an array of little-endian words to a base-64 string
     */
    function binl2b64(binarray)
    {
        var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var str = "";
        for(var i = 0; i < binarray.length * 4; i += 3)
        {
            var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
            for(var j = 0; j < 4; j++)
            {
                if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
                else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
            }
        }
        return str;
    }

    /*
     * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
     * in FIPS PUB 180-1
     * Version 2.1-BETA Copyright Paul Johnston 2000 - 2002.
     * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
     * Distributed under the BSD License
     * See http://pajhome.org.uk/crypt/md5 for details.
     */
    /*
     * Configurable variables. You may need to tweak these to be compatible with
     * the server-side, but the defaults work in most cases.
     */
    var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase     */
    var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance  */
    var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode    */
    /*
     * These are the functions you'll usually want to call
     * They take string arguments and return either hex or base-64 encoded strings
     */
    function hex_sha1(s) {
        return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
    }
    function b64_sha1(s) {
        return binb2b64(core_sha1(str2binb(s), s.length * chrsz));
    }
    function str_sha1(s) {
        return binb2str(core_sha1(str2binb(s), s.length * chrsz));
    }
    function hex_hmac_sha1(key, data) {
        return binb2hex(core_hmac_sha1(key, data));
    }
    function b64_hmac_sha1(key, data) {
        return binb2b64(core_hmac_sha1(key, data));
    }
    function str_hmac_sha1(key, data) {
        return binb2str(core_hmac_sha1(key, data));
    }
    /*
     * Perform a simple self-test to see if the VM is working
     */
    function sha1_vm_test() {
        return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
    }
    /*
     * Calculate the SHA-1 of an array of big-endian words, and a bit length
     */
    function core_sha1(x, len) {
        /* append padding */
        x[len >> 5] |= 0x80 << (24 - len % 32);
        x[((len + 64 >> 9) << 4) + 15] = len;
        var w = Array(80);
        var a = 1732584193;
        var b = -271733879;
        var c = -1732584194;
        var d = 271733878;
        var e = -1009589776;
        for (var i = 0; i < x.length; i += 16) {
            var olda = a;
            var oldb = b;
            var oldc = c;
            var oldd = d;
            var olde = e;
            for (var j = 0; j < 80; j++) {
                if (j < 16) w[j] = x[i + j];
                else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
                var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
                e = d;
                d = c;
                c = rol(b, 30);
                b = a;
                a = t;
            }
            a = safe_add(a, olda);
            b = safe_add(b, oldb);
            c = safe_add(c, oldc);
            d = safe_add(d, oldd);
            e = safe_add(e, olde);
        }
        return Array(a, b, c, d, e);
    }
    /*
     * Perform the appropriate triplet combination function for the current
     * iteration
     */
    function sha1_ft(t, b, c, d) {
        if (t < 20) return (b & c) | ((~b) & d);
        if (t < 40) return b ^ c ^ d;
        if (t < 60) return (b & c) | (b & d) | (c & d);
        return b ^ c ^ d;
    }
    /*
     * Determine the appropriate additive constant for the current iteration
     */
    function sha1_kt(t) {
        return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
    }
    /*
     * Calculate the HMAC-SHA1 of a key and some data
     */
    function core_hmac_sha1(key, data) {
        var bkey = str2binb(key);
        if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
        var ipad = Array(16),
            opad = Array(16);
        for (var i = 0; i < 16; i++) {
            ipad[i] = bkey[i] ^ 0x36363636;
            opad[i] = bkey[i] ^ 0x5C5C5C5C;
        }
        var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
        return core_sha1(opad.concat(hash), 512 + 160);
    }
    /*
     * Add integers, wrapping at 2^32. This uses 16-bit operations internally
     * to work around bugs in some JS interpreters.
     */
    function safe_add(x, y) {
        var lsw = (x & 0xFFFF) + (y & 0xFFFF);
        var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
        return (msw << 16) | (lsw & 0xFFFF);
    }
    /*
     * Bitwise rotate a 32-bit number to the left.
     */
    function rol(num, cnt) {
        return (num << cnt) | (num >>> (32 - cnt));
    }
    /*
     * Convert an 8-bit or 16-bit string to an array of big-endian words
     * In 8-bit function, characters >255 have their hi-byte silently ignored.
     */
    function str2binb(str) {
        var bin = Array();
        var mask = (1 << chrsz) - 1;
        for (var i = 0; i < str.length * chrsz; i += chrsz)
            bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
        return bin;
    }
    /*
     * Convert an array of big-endian words to a string
     */
    function binb2str(bin) {
        var str = "";
        var mask = (1 << chrsz) - 1;
        for (var i = 0; i < bin.length * 32; i += chrsz)
            str += String.fromCharCode((bin[i >> 5] >>> (24 - i % 32)) & mask);
        return str;
    }
    /*
     * Convert an array of big-endian words to a hex string.
     */
    function binb2hex(binarray) {
        var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
        var str = "";
        for (var i = 0; i < binarray.length * 4; i++) {
            str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
        }
        return str;
    }
    /*
     * Convert an array of big-endian words to a base-64 string
     */
    function binb2b64(binarray) {
        var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var str = "";
        for (var i = 0; i < binarray.length * 4; i += 3) {
            var triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
            for (var j = 0; j < 4; j++) {
                if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
                else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
            }
        }
        return str;
    }
</script>

<script>
    function dm_code_user(){
        return {
            usr_id 			: 102224,
            usr_key			: "G83wWWbYm7oXJ4Mynb8OISqJWILmyWmF",
            app_id 			: 302424,
            app_key 		: "CkaPkUIthtLt0EelWnn7BMHEV2BAxvrr",
            pred_type		: 100010018,
        };
    }

    function dm_read_code(img_data) {
        var usr = dm_code_user();
        var usr_id = usr.usr_id;
        var usr_key = usr.usr_key;
        var app_id = usr.app_id;
        var app_key = usr.app_key
        var pred_type = usr.pred_type;

        var curDate = new Date();
        timestamp	= parseInt(curDate.getTime() / 1000).toString();

        function CalcSign(usr_id, usr_key, timestamp){
            md5_chk		= hex_md5(timestamp + usr_key);
            sign_chk	= hex_md5( usr_id + timestamp + md5_chk);
            return sign_chk;
        }

        console.log("开始识别",img_data);
        $.ajax({
            url:'http://pred.fateadm.com/api/capreg',
            type:'POST',
            timeout: 60000,
            data:{
                user_id:usr_id,
                timestamp:timestamp,
                sign:CalcSign( usr_id, usr_key, timestamp),
                app_id:app_id,
                asign:CalcSign( app_id, app_key, timestamp),
                // predict_type:306005000 ,
                predict_type:40400 ,
                img_data:img_data
            },
            success:function (data) {
                console.log('结果',data);
                data = JSON.parse(data);
                console.log('结果',data.RetCode);

                if(data.RetCode==0){
                    rs = JSON.parse(data.RspData);
                    console.log('结果2',rs);
                    $('#dm_code').val(rs.result);
                    //$('#dm_login').trigger('click');
                }
            },
            complete: function (XMLHttpRequest, status) { //求完成后最终执行参数
                if (status == 'timeout') { //超时,status还有success,error等值的情况
                    setTimeout(function () {
                        get_new_code();
                    },500);
                }
            }
        });
    }


    var dm_show = false;
    $.ajax({
        url: 'http://60.223.243.61:28080/admin/',
        type:'GET',
        success:function (data) {
            //console.log('测试是否登录',data);
            if(data.indexOf("如果您没有帐号")!=-1){
                $('#dm_login_box').show();
                //$('#dm_tool_main').hide();
                get_new_code();
            }else{
                $('#dm_login_box').hide();
                var is_auto = localStorage.getItem("dm_auto_start");
                console.log(is_auto);
                if(is_auto==1){
                    start_test();
                }
                $('#dm_tool').trigger('click');
                //$('#dm_tool_main').show();
            }
        }
    });
    $('#dm_tool').on('click',function () {
        if(!dm_show){
            dm_show = true;
            $('#dm_tool').html('点击隐藏');
            $('#dm_main').show();
            $('#dm_code_hand').focus();
        }else{
            dm_show = false;
            $('#dm_tool').html('代码·辅助');
            $('#dm_main').hide();
        }
    });
    //$('#dm_tool').trigger('click');


    function get_new_code() {
        //$('#dm_code').val('读取&识别中,请稍后..');
        //$('#dm_login_tips').html("读取&识别中,请稍后..");

        setTimeout(function () {
            function getBase64Image(img) {
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);
                var dataURL = canvas.toDataURL("image/png");
                return dataURL
                // return dataURL.replace("data:image/png;base64,", "");
            }

            var img = document.createElement('img');
            img.src = 'http://60.223.243.61:28080/jcaptcha.jpg';  //此处自己替换本地图片的地址
            img.onload =function() {
                var data = getBase64Image(img);
                data2 =  data.replace("data:image/png;base64,", "")
                dm_read_code(data2);  //自动登录
                $('#dm_login_code').attr('src',data);
            };
            img.onerror=function (ev) {
                setTimeout(function () {
                    get_new_code();
                },1000);
            };
        },500);
    }

    $('#dm_login_code').on('click',function () {
        get_new_code();
    });

    $('#dm_login').on('click',function () {
        var user = $('#dm_user').val();
        var pass = $('#dm_pass').val();
        var code = $('#dm_code').val();
        var code_hand = $('#dm_code_hand').val();
        console.log(user,pass,code);
        if(code_hand){
            code = code_hand;
        }
        dm_login(user,pass,code);
    });
    function dm_login(username,password,code) {
        localStorage.setItem("dm_user", username);
        localStorage.setItem("dm_pass", password);
        $.ajax({
            url:'http://60.223.243.61:28080/admin/login',
            type:'POST',
            data:{
                username:username,
                password:password,
                jcaptchaCode:code,
                rememberMe:0
            },
            success:function (data) {
                console.log(data);
                if(data.indexOf("账户管理")!=-1){
                    //window.location.reload();
                    window.location.href = "http://60.223.243.61:28080/admin/sys/addbook";
                }else{
                    //$('#dm_login_code').attr('src','http://60.223.243.61:28080/jcaptcha.jpg');
                    $('#dm_login_error').html('登录失败,已重新刷新验证码');
                    get_new_code();
                    $('#dm_code_hand').val('');
                    $('#dm_code_hand').focus();
                }
            }
        });
    }


    Date.prototype.Format = function(fmt) { //author: meizz
        var o = {
            "M+" : this.getMonth() + 1, //月份
            "d+" : this.getDate(), //日
            "h+" : this.getHours(), //小时
            "m+" : this.getMinutes(), //分
            "s+" : this.getSeconds(), //秒
            "S" : this.getMilliseconds()
            //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
        for ( var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1,
                    (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k])
                        .substr(("" + o[k]).length)));
        return fmt;
    }


    var timer;
    var is_running = false;
    $('#dm_test').on('click',function () {
        start_test();
    });


    function start_test() {
        $('#dm_booking').html("");
        if(!is_running){
            var dm_target_screenNo = $('#dm_screenNo').val();
            var dm_target_num = $('#dm_ticket_num').val();
            var dm_target_sfz = $('#dm_sfz_id').val();
            var showDate = $("#dm_date").val().substr(0,10);
            if(!showDate){
                alert("请设置日期");
                return false;
            }
            if(!dm_target_screenNo){
                alert("请设置场次");
                return false;
            }
            if(!dm_target_num){
                alert("请设置张数");
                return false;
            }
            if(!dm_target_sfz){
                alert("请设置身份证号");
                return false;
            }

            localStorage.setItem("dm_date", showDate);
            localStorage.setItem("dm_sfz_id", $('#dm_sfz_id').val());
            localStorage.setItem("dm_ticket_num", dm_target_num);
            localStorage.setItem("dm_target_screenNo", dm_target_screenNo);

            $('#dm_transNo').val($('#transNo').val());

            is_running = true;
            console.log("ddddddddddddd");
            $('#dm_test').html("停止抢票");
            $('#dm_test').css("background","#333");
            var dm_timer = $('#dm_timer').val()*1000;
            var index = 1;
            get_ticket();
            $('#dm_loop_num').val(index++);
            timer = setInterval(function () {
                get_ticket();
                $('#dm_loop_num').val(index++);
            },dm_timer);
        }else{
            is_running = false;
            $('#dm_test').html("开始抢票");
            $('#dm_test').css("background","#00b7ee");
            $('#dm_loop_num').val("已停止");
            try{
                clearInterval(timer);
            }catch (e){}
        }
    }

    $('#dm_save_config').on('click',function () {
        localStorage.setItem("dm_auto_start", $("#dm_auto_start").val());
        localStorage.setItem("dm_date", $("#dm_date").val().substr(0,10));
        localStorage.setItem("dm_sfz_id", $('#dm_sfz_id').val());
        localStorage.setItem("dm_ticket_num", $('#dm_ticket_num').val());
        localStorage.setItem("dm_target_screenNo", $('#dm_screenNo').val());
        localStorage.setItem("dm_timer_order", $('#dm_timer_order').val());

        $('#bookNum').val($('#dm_ticket_num').val());

        $('#dm_save_config').html('正在保存..');
        setTimeout(function () {
            $('#dm_save_config').html('保存配置');
        },500);
    });

    function get_ticket() {
        var dm_target_screenNo = $('#dm_screenNo').val();
        var dm_target_num = $('#dm_ticket_num').val();
        var dm_target_sfz = $('#dm_sfz_id').val();
        var showDate = $("#dm_date").val().substr(0,10);

        $('#bookNum').val(dm_target_num);
        $('#idNo').val(dm_target_sfz);

        $("#showDateStr").val(showDate)
        var saleEndTime = $("#saleEndTime").val();
        $("#screenNo").empty();
        $("#ticketID").empty();
        $.ajax({
            type : 'Get',
            data : {
                "showDate" : showDate,
                "saleEndTime" : saleEndTime
            },
            url : '/admin/sys/addbook/selectShowPlan',
            dataType : "Json",
            success : function(data) {
                console.log("场次信息",data);

                $.each(data, function(i, n) {
                    $("#screenNo").append(
                        " <option value='"+n.screenNo+"'>第 "
                        + n.screenNo
                        + " 场 [开演:"
                        + new Date(n.startTime).Format("hh:mm:ss") + "剩：<font color='red'>"
                        + n.remainNum + "</font>张]</option>");
                });

                var flag=-1;
                $.each(data, function(i, n) {
                    if(n.screenNo == dm_target_screenNo){
                        flag = n.remainNum;
                    }
                });
                $('#dm_screen_remainNum').val(flag);

                $.ajax({
                    type : 'Get',
                    url : '/admin/sys/addbook/getTicketId',
                    dataType : "Json",
                    success : function(data) {
                        $.each(data, function(i, n) {
                            $("#ticketID").append(
                                " <option value='"+n.ticketID+"'>" +  n.ticketName + "</option>");
                        });

                        if(flag==-1){
                            flag='暂无';
                            console.log("无票");
                            $('#book_box').hide();
                        }else if(flag>0 && flag>=dm_target_num){
                            console.log("订票");
                            $('#book_box').show();
                            $('#dm_can_book1').show();
                            start_book(dm_target_num); //订票  按设置数量
                            $('#dm_loop_num').val("已停止,票足够,订票中..");
                            $('#dm_test').trigger('click');
                            playSound();
                        }else if(flag>0 && flag<dm_target_num){
                            console.log("余票不够，要不要",flag);
                            $('#book_box').show();
                            $('#dm_can_book2').show();
                            start_book(flag);  //订票 按余票
                            $('#dm_loop_num').val("已停止,请修改张数后点击【下单】");
                            $('#dm_test').trigger('click');
                            playSound();
                        }
                    }
                });
            }
        });


    }

    $('.dm_tips').on('click',function () {
        $(this).hide();
    });

    $('#dm_book_code_img').on('click',function () {
        get_book_code();
    });

    function get_book_code() {
        $('#dm_book_code').val('');
        $('#dm_booking').html("验证码读取识别中..");
        setTimeout(function () {
            function getBase64Image(img) {
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);
                var dataURL = canvas.toDataURL("image/png");
                return dataURL
                // return dataURL.replace("data:image/png;base64,", "");
            }

            var img = document.createElement('img');
            img.src = 'http://60.223.243.61:28080/jcaptcha.jpg';  //此处自己替换本地图片的地址
            img.onload =function() {
                var data = getBase64Image(img);
                data2 =  data.replace("data:image/png;base64,", "")
                dm_read_book_code(data2);
                $('#dm_book_code_img').attr('src',data);
            };
            img.onerror=function (ev) {
                //alert("图片错误");
                setTimeout(function () {
                    get_book_code();
                },1000);
            };
        },200);
    }

    var timer_to_order;
    function dm_read_book_code(img_data) {
        var usr = dm_code_user();
        var usr_id = usr.usr_id;
        var usr_key = usr.usr_key;
        var app_id = usr.app_id;
        var app_key = usr.app_key
        var pred_type = usr.pred_type;

        var curDate = new Date();
        timestamp	= parseInt(curDate.getTime() / 1000).toString();

        function CalcSign(usr_id, usr_key, timestamp){
            md5_chk		= hex_md5(timestamp + usr_key);
            sign_chk	= hex_md5( usr_id + timestamp + md5_chk);
            return sign_chk;
        }

        //console.log("开始识别",img_data);
        clearTimeout(timer_to_order);
        $.ajax({
            url:'http://pred.fateadm.com/api/capreg',
            type:'POST',
            timeout: 60000,
            data:{
                user_id:usr_id,
                timestamp:timestamp,
                sign:CalcSign( usr_id, usr_key, timestamp),
                app_id:app_id,
                asign:CalcSign( app_id, app_key, timestamp),
                //predict_type:306005000 ,
                predict_type:40400 ,
                img_data:img_data
            },
            success:function (data) {
                console.log('结果',data);
                data = JSON.parse(data);
                console.log('结果',data.RetCode);

                if(data.RetCode==0){
                    rs = JSON.parse(data.RspData);
                    console.log('结果2',rs);
                    $('#dm_book_code').val(rs.result);


                    var holdon = $('#dm_timer_order').val();
                    $('#dm_booking').html("预定成功,冻结"+holdon+"秒付款");
                    timer_to_order = setTimeout(function () {
                        $('#dm_booking').html("提交订单中..");
                        console.log("提交订单中..");
                        order_pay();
                    },holdon*1000);
                }else{
                    $('#dm_booking').html("需手动提交");
                }
            },
            complete: function (XMLHttpRequest, status) { //求完成后最终执行参数
                if (status == 'timeout') { //超时,status还有success,error等值的情况
                    setTimeout(function () {
                        get_book_code();
                    },500);
                }
            }
        });
    }

    $('#dm_book').on('click',function () {
        var book_num = $('#dm_ticket_num').val();
        start_book(book_num);
    });

    function start_book(book_num) {
        var maxNum = $('#maxNum').val();
        if(book_num>maxNum){
            book_num = maxNum;
        }

        $('#dm_book_num').val(book_num);

        setTimeout(function () {
            $('#dm_booking').html("预提交订单...");

            $.ajax({
                url:'http://60.223.243.61:28080/admin/sys/addbook/addNewBook',
                type:'POST',
                data:{
                    maxNum:maxNum,
                    transNo:$('#dm_transNo').val(),
                    showDateStr:$("#dm_date").val().substr(0,10),
                    guideID:$('#guideID').val(),
                    guideName:$('#guideName').val(),
                    bookNum:book_num,
                    mobilePhone:'',
                    idNo:$('#dm_sfz_id').val(),
                    remarks:'',
                    undefined:'提交',
                    screenNo:$('#dm_screenNo').val(),
                    ticketID:$('#ticketID').val(),
                    touristProvince:'请选择',
                    touristCity:'请选择'
                },
                success:function (data) {
                    $('#dm_booking').html("预提交成功,正式提交中..");
                    console.log(data);
                    if(data.ret==0){
                        var preOrderId = data.msg;
                        $('#dm_book_order_id').val(preOrderId);
                        get_book_code();
                    }else{
                        $('#dm_booking').html(data.msg+"【请手动操作】");
                    }
                }
            });
        },500);
    }

    $('#dm_book_pay').on('click',function () {
        get_book_code();
    });

    function order_pay() {
        $.ajax({
            url:'http://60.223.243.61:28080/admin/sys/addbook/submitBook',
            type:'POST',
            data:{
                autoId:$('#dm_book_order_id').val(),
                captchaCode:$('#dm_book_code').val()
            },
            success:function (data2) {
                console.log(data2);
                if(data2.ret==0){
                    $('#dm_booking').html(data2.msg);
                }else{
                    $('#dm_booking').html(data2.msg+"【请手动操作】");
                }
            }
        });
    }


    $('#dm_reload').on('click',function () {
        window.location.reload();
    });

    $('#dm_rebook').on('click',function () {
        $('#dm_booking').html("");
        $('#book_box').hide();

        $.ajax({
            url:'http://60.223.243.61:28080/admin/sys/addbook',
            type:'GET',
            success:function (data) {
                //console.log(data);
                //str = data.match(/tran(\S*)/);
                //console.log(str);
                $('.wrapper').remove();
                $('body').append(data);
            }
        });
    });


    $('#dm_book_pay_hand').on('click',function () {
        order_pay_hand();
    });


    $('#dm_logout').on('click',function () {
        window.location.href="http://60.223.243.61:28080/admin/logout";
    });

    function order_pay_hand() {
        $.ajax({
            url:'http://60.223.243.61:28080/admin/sys/addbook/submitBook',
            type:'POST',
            data:{
                autoId:$('#dm_book_order_id').val(),
                captchaCode:$('#dm_book_code_hand').val()
            },
            success:function (data2) {
                console.log(data2);
                if(data2.ret==0){
                    $('#dm_booking').html(data2.msg);
                }else{
                    $('#dm_booking').html(data2.msg+"【请手动操作】");
                }
            }
        });
    }


    function playSound(){
        document.getElementById("MyAudio1").play();
        setTimeout(function () {
            document.getElementById("MyAudio2").play();
            setTimeout(function () {
                document.getElementById("MyAudio2").play();
            },3000);
        },1000);
    }
</script>